<template>
	<div class="article-edit">
		<el-card class="!border-none" shadow="never">
			<el-page-header :content="$route.meta.title" @back="$router.back()" />
		</el-card>
		<el-card class="mt-4 !border-none" shadow="never">
			<el-tabs v-model="lang" @tab-change="handChange">
				<el-tab-pane v-for="(item, index) in languages.list" :key="index" :label="item.name" :name="item.symbol"
					lazy></el-tab-pane>
			</el-tabs>
			<el-form ref="formRef" class="ls-form" :model="formData" label-width="85px" :rules="rules">
				<div class="xl:flex">
					<div>
						<el-form-item label="文章标题" prop="title">
							<div class="w-80">
								<el-input v-model="formData.title" placeholder="请输入文章标题" type="textarea"
									:autosize="{ minRows: 3, maxRows: 3 }" maxlength="64" show-word-limit clearable />
								<el-button type="primary" size="small" v-if="active!=0" @click="handTranslation('title')" :loading="loadingTran">翻译</el-button>
							</div>
						</el-form-item>
						<el-form-item label="文章栏目" prop="cid">
							<el-select class="w-80" v-model="formData.cid" placeholder="请选择文章栏目" clearable>
								<el-option v-for="item in optionsData.article_cate" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="文章简介" prop="desc">
							<div class="w-80">
								<el-input v-model="formData.desc" placeholder="请输入文章简介" type="textarea"
									:autosize="{ minRows: 3, maxRows: 6 }" :maxlength="200" show-word-limit clearable />
							</div>
						</el-form-item> -->
						<!-- <el-form-item label="摘要" prop="abstract">
							<div class="w-80">
								<el-input type="textarea" :autosize="{ minRows: 6, maxRows: 6 }"
									v-model="formData.abstract" maxlength="200" show-word-limit clearable />
							</div>
						</el-form-item> -->
						<!-- <el-form-item label="文章封面" prop="image">
							<div>
								<div>
									<material-picker v-model="formData.image" :limit="1" />
								</div>
								<div class="form-tips">建议尺寸：240*180px</div>
							</div>
						</el-form-item> -->
						<!-- <el-form-item label="作者" prop="author">
							<div class="w-80">
								<el-input v-model="formData.author" placeholder="请输入作者名称" />
							</div>
						</el-form-item> -->
						<el-form-item label="排序" prop="sort">
							<div>
								<el-input-number v-model="formData.sort" :min="0" :max="9999" />
								<div class="form-tips">默认为0， 数值越大越排前</div>
							</div>
						</el-form-item>
						<!-- <el-form-item label="初始浏览量" prop="click_virtual">
							<div>
								<el-input-number v-model="formData.click_virtual" :min="0" />
							</div>
						</el-form-item> -->
						<el-form-item label="文章状态" required prop="is_show">
							<el-radio-group v-model="formData.is_show">
								<el-radio :label="1">显示</el-radio>
								<el-radio :label="0">隐藏</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="首页公告" required prop="is_popup" v-if="formData.cid == 5">
							<el-radio-group v-model="formData.is_popup">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="首页滚动" required prop="is_notice" v-if="formData.cid == 5">
							<el-radio-group v-model="formData.is_notice">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="系统通知" required prop="is_sys_notice" v-if="formData.cid == 5">
							<div>
								<el-radio-group v-model="formData.is_sys_notice">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
								<div class="form-tips">开启后，发布文章后将通知给所有用户</div>
							</div>
							
							
						</el-form-item>
					</div>
					<div class="xl">
						<el-form-item label="文章内容" prop="content">
							<editor v-model="formData.content" :height="667" :width="375" />
						</el-form-item>
					</div>
				</div>
			</el-form>
		</el-card>
		<footer-btns>
			<el-button type="primary" @click="handleSave">保存</el-button>
		</footer-btns>
	</div>
</template>

<script lang="ts" setup name="articleListsEdit">
	import type { FormInstance } from 'element-plus'
	import { useDictOptions } from '@/hooks/useDictOptions'
	import { articleDetail, articleEdit, articleAdd, articleCateAll } from '@/api/article'
	import { translation } from '@/api/translation'
	import { apiLanguageAll } from '@/api/setting/language'
	import useMultipleTabs from '@/hooks/useMultipleTabs'
	import feedback from '@/utils/feedback'

	const languages = reactive({
		list: [{
			id: '',
			name: '',
			symbol: ''
		}],
		symbol: ''
	})

	const active = ref(0);
	const lang = ref("");
	const lang_1 = ref("");//切换前一个
	let langs = reactive([]);

	const route = useRoute()
	const router = useRouter()
	const formData = reactive({
		id: '',
		title: '',
		image: '',
		cid: '',
		desc: '',
		author: '',
		content: '',
		click_virtual: 0,
		sort: 0,
		is_show: 1,
		is_notice: 0,
		is_popup: 0,
		is_sys_notice:0,
		abstract: '',
		langs: []
	})

	const { removeTab } = useMultipleTabs()
	const formRef = shallowRef<FormInstance>()
	const rules = reactive({
		title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
		cid: [{ required: true, message: '请选择文章栏目', trigger: 'blur' }]
	})

	const getDetails = async () => {
		const data = await articleDetail({
			id: route.query.id
		})
		Object.keys(formData).forEach((key) => {
			//@ts-ignore
			formData[key] = data[key]
		})
		langs = data['langs'];
	}

	const { optionsData } = useDictOptions<{
		article_cate : any[]
	}>({
		article_cate: {
			api: articleCateAll
		}
	})

	const handleSave = async () => {
		await formRef.value?.validate()
		//数组存储
		let arr = {
			'lang': lang.value,
			'abstract': formData.abstract,
			'content': formData.content,
			'desc': formData.desc,
			'image': formData.image,
			'title': formData.title
		}
		
		//数组更新
		let array = pushArr(langs, lang.value,arr);
		langs = array;
		
		//查询首个语言是否填写
		let exists = false;
		let langs_key = 0;
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == languages.list[0]['symbol']) {
				if(langs[key]['title']!=""){
					exists = true;
					langs_key = parseInt(key);
				}
			}
		})
		if(!exists) return feedback.msgError('首个语言必填');
		//输入初始化
		let arr2 = langs[langs_key];
		Object.keys(arr2).forEach((key) => {
			//@ts-ignore
			formData[key] = arr2[key]
		})
		
		formData.langs = langs;

		if (route.query.id) {
			await articleEdit(formData)
		} else {
			await articleAdd(formData)
		}
		removeTab()
		router.back()
	}

	route.query.id && getDetails()

	const getData = async () => {
		const data = await apiLanguageAll()
		languages.list = data;
		languages.symbol = data[0]['symbol'];
		lang.value = languages.symbol;
	}

	//数组替换，存在替换，不存在追加
	const pushArr = (arr : any, lang : string, params : any) => {
		let result = false;
		Object.keys(arr).forEach((key) => {
			if (arr[key]['lang'] == lang) {
				arr[key] = params;
				result = true;
			}
		})

		if (!result) {
			arr.push(params);
		}
		return arr;
	}
	
	//标签切换
	const handChange = async (data : string) => {
		let lang_last = lang_1.value;
		lang_1.value = data
		const index = languages.list.findIndex((item) => item.symbol === data);
		active.value = index;

		//数组存储
		if (lang_last != "") {
			let arr = {
				'lang': lang_last,
				'abstract': formData.abstract,
				'content': formData.content,
				'desc': formData.desc,
				'image': formData.image,
				'title': formData.title
			}
			let array = pushArr(langs,lang_last,arr);
			langs = array;
		}
		//输入初始化
		let arr2 = {
			'lang': "",
			'abstract': "",
			'content': "",
			'desc': "",
			'image': "",
			'title': ""
		}
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == data) {
				arr2 = langs[key];
			}
		})
		if (lang_last != "") {
			Object.keys(arr2).forEach((key) => {
				//@ts-ignore
				formData[key] = arr2[key]
			})
		}
		if (localStorage.getItem('trans_auto') == '1' && formData.title == '' && active.value != 0) {
			handTranslation('title')
		}
	}
	
	//翻译
	const loadingTran = ref(false);
	const loadingTran2= ref(false);
	const handTranslation = async (field : string) => {
		
		//查询首个语言是否填写
		let exists = false;
		let langs_key = 0;
		
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == languages.list[0]['symbol']) {
				if(langs[key][field]!=""){
					exists = true;
					langs_key = parseInt(key);
				}
			}
		})
		if(!exists) return feedback.msgError('首个语言必填');
		const qArray = [langs[langs_key][field]]
		
		if(field == 'title'){
			loadingTran.value = true;
		}else{
			loadingTran2.value = true;
		}
		const res = await translation({
			qArray: qArray,
			from:languages.list[0]['trans_symbol'],
			to:languages.list[active.value]['trans_symbol']
		})
		formData[field] = res['result'][0]['translation'];
		
		if(field == 'title'){
			loadingTran.value = false;
		}else{
			loadingTran2.value = false;
		}
		
	}
	getData()
</script>